<template>
  <div>
    <el-dialog
      :title="$t('piLiangXinZeng')"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div class="flex-card">
        <div style="flex: 1; display: flex; gap: 15px;">
          <template v-if="!isEdit">
            <el-button
              type="primary"
              size="small"
              @click="downloadTemplate"
            >{{ $t('downloadTemplate') }}</el-button>
            <el-upload
              action
              :http-request="handleUploadForm"
              :show-file-list="false"
              :disabled="loading"
            >
              <el-button
                type="primary"
                size="small"
                :loading="loading"
              >{{ importText }}</el-button>
            </el-upload>
          </template>
        </div>
        <div v-show="countObj.totalNum>0">
          <span>导入数量：{{ countObj.totalNum }}</span>
          <span>成功：{{ countObj.successNum }}</span>
          <span>失败：{{ countObj.failNum }}</span>
        </div>
      </div>
      <el-form v-if="formData.errList.length>0" ref="formRef" :model="formData" :rules="rules">
        <el-table :data="formData.errList" border style="margin-top: 15px;" max-height="500">
          <el-table-column label="SKU编码" prop="skuCode" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuCode'" :rules="rules.skuCode">
                <el-input v-model="scope.row.skuCode" placeholder="请输入SKU编码" maxlength="80" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="storeName" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.storeName'" :rules="rules.storeName">
                <el-input v-model="scope.row.storeName" placeholder="请输入商品名称" maxlength="200" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品品类编码" prop="categoryCode" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.categoryCode'" :rules="rules.categoryCode">
                <el-input v-model="scope.row.categoryCode" placeholder="请输入商品品类编码" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="品牌编码" prop="brandCode" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.brandCode'" :rules="rules.brandCode">
                <el-input v-model="scope.row.brandCode" placeholder="请输入品牌编码" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="折扣价" prop="price" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.price'" :rules="rules.price">
                <el-input-number v-model.number="scope.row.price" type="number" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuZheKouJia')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="原价" prop="originalPrice" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.originalPrice'" :rules="rules.originalPrice">
                <el-input-number v-model="scope.row.originalPrice" type="number" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuYuanJia')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品重（kg）" prop="skuWeight" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuWeight'" :rules="rules.skuWeight">
                <el-input-number v-model="scope.row.skuWeight" type="number" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuZhongLiang')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="长(cm)" prop="skuWidth" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuLength'" :rules="rules.skuLength">
                <el-input-number v-model="scope.row.skuLength" type="number" :max="99999999.99" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="宽(cm)" prop="skuWidth" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuWidth'" :rules="rules.skuWidth">
                <el-input-number v-model="scope.row.skuWidth" type="number" :max="99999999.99" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="高(cm)" prop="skuHeight" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuHeight'" :rules="rules.skuHeight">
                <el-input-number v-model="scope.row.skuHeight" type="number" :max="99999999.99" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="颜色" prop="skuColor" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuColor'" :rules="rules.skuColor">
                <el-input v-model="scope.row.skuColor" placeholder="请输入颜色" maxlength="50" clearable />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="型号" prop="skuModel" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.skuModel'" :rules="rules.skuModel">
                <el-input v-model="scope.row.skuModel" placeholder="请输入型号" maxlength="50" clearable />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="HSCODE" prop="hsCode" min-width="220">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.hsCode'">
                <el-input v-model="scope.row.hsCode" placeholder="请输入HSCODE" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="是否带电" prop="electricityFlag" min-width="100">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.electricityFlag'" :rules="rules.electricityFlag">
                <el-switch
                  v-model="scope.row.electricityFlag"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="Y"
                  inactive-value="N"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库存数" prop="stock" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.stock'" :rules="rules.stock">
                <el-input-number v-model="scope.row.stock" type="number" :precision="0" :max="99999999" controls-position="right" :placeholder="$t('qingShuRuKuCunShu')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品图片url-1" prop="image" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.image'" :rules="rules.image">
                <el-input v-model="scope.row.image" placeholder="请输入商品图片url-1" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品图片url-2" prop="flatPattern" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.flatPattern'" :rules="rules.flatPattern">
                <el-input v-model="scope.row.flatPattern" placeholder="请输入商品图片url-2" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品图片url-3" prop="sliderImage" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.sliderImage'" :rules="rules.sliderImage">
                <el-input v-model="scope.row.sliderImage" placeholder="请输入商品图片url-3" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="商品详情" prop="storeInfo" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.storeInfo'" :rules="rules.storeInfo">
                <el-input v-model="scope.row.storeInfo" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" placeholder="请输入商品详情" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="错误信息" prop="errorInfo" min-width="220" fixed="right" />
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="delFn(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span v-if="formData.errList.length>0" slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  productImport,
  downloadImportTemplateApi,
  saveBatchProductApi,
  commonImportApi
} from '@/api/store'
const reg = /^[^\u4e00-\u9fa5]+$/
export default {
  data() {
    return {
      dialogVisible: false,
      importText: '批量导入',
      loading: false,
      countObj: {
        failNum: 0,
        successNum: 0,
        totalNum: 0
      },
      formData: {
        errList: []
      },
      rules: {
        'storeName': [
          { required: true, message: this.$t('qingShuRuShangPinMingCheng'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 商品名称
        'skuCode': [
          { required: true, message: '请输入SKU编码', trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 商品id
        'categoryCode': { required: true, message: '请输入商品品类编码', trigger: ['blur', 'change'] }, // 商品分类
        'brandCode': [
          { required: true, message: this.$t('qingXuanZePinPai'), trigger: 'change' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 品牌
        'price': [{ required: true, message: this.$t('qingShuRuZheKouJia'), trigger: ['blur', 'change'] }], // 折扣价
        'originalPrice': [{ required: true, message: this.$t('qingShuRuYuanJia'), trigger: ['blur', 'change'] }], // 原价
        'skuLength': [{ required: true, message: '请输入长度', trigger: ['blur', 'change'] }], // 长度
        'skuWidth': [{ required: true, message: '请输入宽度', trigger: ['blur', 'change'] }], // 长度
        'skuHeight': [{ required: true, message: '请输入高度', trigger: ['blur', 'change'] }], // 长度
        'skuWeight': [{ required: true, message: this.$t('qingShuRuZhongLiang'), trigger: ['blur', 'change'] }], // 重量
        'skuColor': [
          { required: true, message: this.$t('qingShuRuYanSe'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 颜色
        'skuModel': [
          { required: true, message: this.$t('qingShuRuXingHao'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 型号
        'image': { required: true, message: this.$t('qingShangChuanZhuTu'), trigger: 'blur' }, // 主图
        'flatPattern': { required: true, message: this.$t('qingShangChuanZhanShiTu'), trigger: 'blur' }, // 展示图
        'sliderImage': { required: true, message: this.$t('qingShangChuanLunBoTu'), trigger: 'blur' }, // 轮播图
        'stock': { required: true, message: this.$t('qingShuRuKuCunShu'), trigger: ['blur', 'change'] }, // 库存数
        'hsCode': [{ trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }],
        storeInfo: [
          { required: true, message: '请输入商品详情', trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ]
      },
      isEdit: false
    }
  },
  methods: {
    renderHeader(h, obj) {
      return h('span', { class: 'cy-table-require' }, obj.column.label)
    },
    handleUploadForm(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      this.importText = '导入中...'
      this.loading = true
      productImport(formData).then(res => {
        this.formData.importKey = res
        this.commonImportFn(res)
      })
    },
    // 查询导入结果 无结果时间隔3秒再次查询
    commonImportFn(id) {
      commonImportApi(id).then(res => {
        if (res) {
          this.handleData(res)
        } else {
          setTimeout(() => {
            this.commonImportFn(id)
          }, 3000)
        }
      })
    },
    downloadTemplate() {
      downloadImportTemplateApi().then(res => {
        const blob = new Blob([res.file], { type: 'application/octet-stream' })// res.data为文件流文件
        this.$download.saveAs(blob, res.fileName)
      })
    },
    show(data) {
      this.dialogVisible = true
      if (data) {
        this.isEdit = true
        this.formData.importKey = data.importKey
        this.handleData(data)
      }
    },
    handleClose() {
      this.formData.errList = []
      this.countObj = {
        failNum: 0,
        successNum: 0,
        totalNum: 0
      }
      this.importText = '批量导入'
      this.loading = false
      this.dialogVisible = false
      this.isEdit = false
      this.$emit('getList')
    },
    onSubmit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          saveBatchProductApi({ productImportList: this.formData.errList, importKey: this.formData.importKey }).then(res => {
            loading.close()
            res.errors = res.errorStoreProductList
            this.handleData(res)
          }).finally(() => {
            loading.close()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleData(data) {
      this.importText = '批量导入'
      this.loading = false
      if (data.failNum > 0) {
        this.formData.errList = data.errors
        this.countObj = {
          failNum: data.failNum,
          successNum: data.successNum,
          totalNum: data.totalNum
        }
      } else {
        this.$message.success(this.$t('caoZuoChengGong'))
        this.$emit('getList')
        this.handleClose()
      }
    },
    delFn(index) {
      this.formData.errList.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.flex-card {
  display: flex;
  justify-content: space-between;
}

::v-deep{
  .cy-table-require::before {
    content: "*";
    color: red;
  }
}

</style>
